package com.example.demo.utils;


// 用来共享图片文件的url，用到了异步编程工具（解决调用时机问题）

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

public class FileUrlStore {

    private static final ConcurrentHashMap<String, CompletableFuture<String>> fileUrlMap = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<String, CountDownLatch> latchMap = new ConcurrentHashMap<>();

    public static void storeFileUrlFuture(String fileKey, CompletableFuture<String> future) {
        fileUrlMap.put(fileKey, future);
        CountDownLatch latch = new CountDownLatch(1);
        latchMap.put(fileKey, latch);
        future.thenAccept(fileUrl -> {
            System.out.println("文件链接已存储: " + fileUrl);
            latch.countDown();  // 任务完成，计数器减1
        }).exceptionally(ex -> {
            System.err.println("存储文件链接时发生错误: " + ex.getMessage());
            latch.countDown(); // 任务失败，计数器减1
            return null;
        });
        System.out.println("存储了 fileKey: " + fileKey);
    }

    public static CompletableFuture<String> getFileUrlFuture(String fileKey) {
        return fileUrlMap.get(fileKey);
    }

    public static void awaitFileUrlFuture(String fileKey) throws InterruptedException {
        CountDownLatch latch = latchMap.get(fileKey);
        if (latch != null) {
            latch.await();  // 等待任务完成
        }
        System.out.println("等待结束 fileKey: " + fileKey);
    }

}
